package com.flyduck.security;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.flyduck.entity.SysUser;
import com.flyduck.manager.SysPermissionCacheManager;
import com.flyduck.manager.SysPermissionManager;
import com.flyduck.mapper.SysUserMapper;
import com.flyduck.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * UserDetailServiceImpl
 * </p>
 *
 * @author flyduck
 * @since 2024-05-29
 */
@Service
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private SysPermissionCacheManager sysPermissionCacheManager;
    @Autowired
    private RedisUtils redisUtils;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        SysUser sysUser = sysUserMapper.selectOne(
                new LambdaQueryWrapper<SysUser>()
                        .eq(SysUser::getUsername, username)
        );
        if (sysUser == null) {
            throw new UsernameNotFoundException("用户名或密码不正确");
        }

        List<String> permissionList =  sysPermissionCacheManager.getPermissionListByUserId(sysUser.getId());
        List<SimpleGrantedAuthority> authorityList = new ArrayList<>();
        if(CollectionUtil.isNotEmpty(permissionList)){
            authorityList = permissionList.stream()
                    .map(SimpleGrantedAuthority::new)
                    .collect(Collectors.toList());
        }

        return new CustomUser(sysUser.getId(),
                sysUser.getUsername(),
                sysUser.getPassword(),
                authorityList);
    }
}
